﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewDataBusiness;
using Tools;
using System.Web.Script.Serialization;
using System.Threading;
using System.Configuration;
using System.IO;

namespace Frame.Controllers
{
    public class ViewProcessController : Controller
    {
        [HttpGet]
        public ActionResult Show(string ViewForder, string ViewName, string KeyA, string KeyB, string KeyC, string KeyD)
        {
            //验证登陆
            string UserID = SessionKey.CheckKeyThrow();
            //异步登陆
            AsynchronousLogin.CheckAsynchronousLoginThrow();
            //获取视图设置
            ViewSetting viewSetting = ViewBusiness.LoadViewSetting(ViewForder, ViewName);
            viewSetting.UserID = UserID;
            viewSetting.UserName = Tools.SessionKey.GetUsername();
            viewSetting.Permissions = Request.QueryString["Permissions"];
            viewSetting.ViewForder = ViewForder;
            viewSetting.ViewName = ViewName;
            viewSetting.SID = Session.SessionID;
            viewSetting.KeyList = new Dictionary<string, string>() { { "KeyA", KeyA }, { "KeyB", KeyB }, { "KeyC", KeyC }, { "KeyD", KeyD } };
            //设置约定参数
            viewSetting.GetList = new Dictionary<string, string>();
            foreach (string m in Request.QueryString.Keys)
                switch (m)
                {
                    case "AsynchronousLoginKey":
                        break;
                    case "Permissions":
                        break;
                    default:
                        viewSetting.GetList.Add(m, Request.QueryString[m]);
                        break;
                }
            //设置约定返回地址（专为列表设置）
            viewSetting.UrlAction = AsynchronousLogin.GetAsynchronousLoginUrl(Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("&AsynchronousLoginKey=")).Replace("ViewProcess/Show/", "ViewProcess/Action/"), Request.QueryString["Permissions"]);
            viewSetting.UrlUploadify = AsynchronousLogin.GetAsynchronousLoginUrl(Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("&AsynchronousLoginKey=")).Replace("ViewProcess/Show/", "ViewProcess/Uploadify/"), Request.QueryString["Permissions"]);
            viewSetting.UrlDown = AsynchronousLogin.GetAsynchronousLoginUrl(Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("&AsynchronousLoginKey=")).Replace("ViewProcess/Show/", "ViewProcess/Down/"), Request.QueryString["Permissions"]);
            if (Request.QueryString["UrlReferrer"] == null)
                if (Request.UrlReferrer.AbsoluteUri.IndexOf("SearchKey=") > -1 && Request.UrlReferrer.AbsoluteUri.IndexOf("SortName=") > -1 && Request.UrlReferrer.AbsoluteUri.IndexOf("SortOrder=") > -1 && Request.UrlReferrer.AbsoluteUri.IndexOf("MaxRecord=") > -1 && Request.UrlReferrer.AbsoluteUri.IndexOf("StartRecord=") > -1)
                {
                    string[] URL = Request.UrlReferrer.AbsoluteUri.Split(new string[] { "&", "?", "=" }, StringSplitOptions.None);
                    for (int i = 1; i < URL.Length; i += 2)
                        switch (URL[i])
                        {
                            case "AsynchronousLoginKey":
                                break;
                            case "Permissions":
                                break;
                            case "MaxRecord":
                                URL[i] = "BackMaxRecord";
                                if (Request.QueryString["MaxRecord"] != null)
                                    URL[i + 1] = Server.UrlEncode(Request.QueryString["MaxRecord"]);
                                break;
                            default:
                                if (Request.QueryString[URL[i]] != null)
                                    URL[i + 1] = Server.UrlEncode(Request.QueryString[URL[i]]);
                                break;
                        }
                    viewSetting.UrlReferrer = URL[0] + "?" + URL[1] + "=" + URL[2];
                    for (int i = 3; i < URL.Length; i += 2)
                        if (URL[i] != "AsynchronousLoginKey")
                            viewSetting.UrlReferrer += "&" + URL[i] + "=" + URL[i + 1];
                    viewSetting.UrlReferrer = AsynchronousLogin.GetAsynchronousLoginUrl(viewSetting.UrlReferrer, Request.QueryString["Permissions"]);
                }
                else
                {
                    viewSetting.UrlReferrer = Request.UrlReferrer == null ? "" : Request.UrlReferrer.AbsoluteUri;
                }
            else
                viewSetting.UrlReferrer = Request.QueryString["UrlReferrer"];

            //数据给工厂加工    
            List<string> PermissionList = new List<string>(viewSetting.Permissions.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
            if (!PermissionList.Contains(""))
                PermissionList.Add("");
            Factory.ViewFactory(viewSetting, ControllerContext.RouteData.Values, PermissionList);
            //格式化视图数据
            viewSetting.JsonString = new JavaScriptSerializer().Serialize(viewSetting);
            ViewBag.FilePath = "/Views/" + ViewForder + "/" + ViewName + ".json";
            //视图和数据显示
            return View("/Views/" + ViewForder + "/" + ViewName + ".cshtml", viewSetting);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Action(string ViewForder, string ViewName)
        {
            try
            {
                //验证登陆                 
                string UserID = SessionKey.CheckKeyThrow();
                //异步登陆
                AsynchronousLogin.CheckAsynchronousLoginThrow();
                //获取视图设置
                ViewSetting viewSetting = ViewBusiness.LoadViewSetting(ViewForder, ViewName);
                viewSetting.UserID = UserID;
                viewSetting.Permissions = Request.QueryString["Permissions"];
                viewSetting.ViewForder = ViewForder;
                viewSetting.ViewName = ViewName;
                //获取操作参数
                List<List<ActionOperation>> ActionParameters = new JavaScriptSerializer().Deserialize<List<List<ActionOperation>>>(Request.Form["ActionParameters"]);
                //数据给工厂加工      
                List<string> PermissionList = new List<string>(viewSetting.Permissions.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
                if (!PermissionList.Contains(""))
                    PermissionList.Add("");
                List<object> returnData = Factory.ActionFactory(viewSetting, ControllerContext.RouteData.Values, PermissionList, ActionParameters);
                //数据返回到视图
                return Json(new { Success = true, Message = "操作成功。", ReturnData = returnData });
            }
            catch (Exception ex)
            {
                return Json(new { Success = false, Message = ex.Message });
            }
        }
                                     
        [HttpPost]
        public ContentResult Uploadify(HttpPostedFileBase FileData, string ViewForder, string ViewName)
        {                                                         
            try
            {
                //验证登陆                 
                string UserID = SessionKey.CheckKeyThrow(Request.Form["SID"]);
                //异步登陆
                AsynchronousLogin.CheckAsynchronousLoginThrow(Request.Form["SID"]);
                //获取视图设置
                ViewSetting viewSetting = ViewBusiness.LoadViewSetting(ViewForder, ViewName);
                viewSetting.UserID = UserID;
                viewSetting.Permissions = Request.QueryString["Permissions"];
                viewSetting.ViewForder = ViewForder;
                viewSetting.ViewName = ViewName;
                //获取操作参数
                List<List<ActionOperation>> ActionParameters = new JavaScriptSerializer().Deserialize<List<List<ActionOperation>>>(Request.Form["ActionParameters"]);
                //数据给工厂加工      
                List<string> PermissionList = new List<string>(viewSetting.Permissions.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
                if (!PermissionList.Contains(""))
                    PermissionList.Add("");
                return Content(Factory.ActionUploadify(viewSetting, ControllerContext.RouteData.Values, PermissionList, ActionParameters, FileData));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
        [HttpGet]
        public FileStreamResult Down(string ViewForder, string ViewName)
        {
            //获取视图设置
            ViewSetting viewSetting = ViewBusiness.LoadViewSetting(ViewForder, ViewName);
            viewSetting.Permissions = Request.QueryString["Permissions"];
            //获取操作参数
            string OperationKey =Request.QueryString["OperationKey"];
            string FileName = Request.QueryString["FileName"];

            if (FileName.IndexOf("^OL-") == -1){
                //验证登陆                 
                SessionKey.CheckKeyThrow();
                //异步登陆
                AsynchronousLogin.CheckAsynchronousLoginThrow();
                //数据给工厂加工      
                List<string> PermissionList = new List<string>(viewSetting.Permissions.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
                if (!PermissionList.Contains(""))
                    PermissionList.Add("");

                if (!PermissionList.Contains(viewSetting.Operations[OperationKey].Permission) && viewSetting.UserID != "Administrator")
                    throw new Exception("没有权限：" + viewSetting.Operations[OperationKey].Permission + "，无法进行操作：" + OperationKey + "。");
            }
            
            Dictionary<string, string> PathObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(viewSetting.Operations[OperationKey].JsonParameter);
            string FilePath = Factory.GetPath(ControllerContext.RouteData.Values, PathObj["基目录"], PathObj["子目录"], "InternalFiles") + "\\" + FileName;
            if (System.IO.File.Exists(FilePath))
                return File(new FileStream(FilePath, FileMode.Open), "application/octet-stream", Server.UrlEncode(FileName.Substring(FileName.LastIndexOf("-") + 1)));
            else
                throw new Exception("没有找到该文件或者你没有权限下载该文件！");
        }
    }
}
